package service

import (
	"context"
	"shop-demo/app/order/service/internal/biz"

	pb "shop-demo/api/order/v1"
)

type OrderService struct {
	uc *biz.OrderUseCase
	pb.UnimplementedOrderServer
}

func NewOrderService(uc *biz.OrderUseCase) *OrderService {
	return &OrderService{uc: uc}
}

func (s *OrderService) CreateOrder(ctx context.Context, req *pb.CreateOrderReq) (*pb.CreateOrderReply, error) {

	details := make([]*biz.Product, 0, len(req.Products))

	for _, product := range req.Products {
		details = append(details, &biz.Product{
			Id:   product.Id,
			Name: product.Name,
			Num:  product.Num,
		})
	}

	order, err := s.uc.CreateOrder(ctx, &biz.Order{
		Id:      req.UserId,
		Details: details,
	})
	if err != nil {
		return nil, err
	}
	return &pb.CreateOrderReply{
		Id:     order.Id,
		UserId: order.UserId,
	}, nil
}
func (s *OrderService) GetOrder(ctx context.Context, req *pb.GetOrderReq) (*pb.GetOrderReply, error) {
	order, err := s.uc.GetOrder(ctx, req.Id)
	if err != nil {
		return nil, err
	}

	return &pb.GetOrderReply{Id: order.Id, UserId: order.UserId}, nil
}
func (s *OrderService) ListOrder(ctx context.Context, req *pb.ListOrderReq) (*pb.ListOrderReply, error) {
	orders, err := s.uc.ListOrder(ctx, req.PageNum, req.PageSize)
	if err != nil {
		return nil, err
	}
	replyOrders := make([]*pb.ListOrderReply_Order, 0, len(orders))
	for _, order := range orders {
		replyOrders = append(replyOrders, &pb.ListOrderReply_Order{
			Id:     order.Id,
			UserId: order.UserId,
		})
	}
	return &pb.ListOrderReply{Orders: replyOrders}, nil
}
